package com.tansun.easycare.rule.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author WY
 */
public class HttpUtils {
    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 规则在线部署
     *
     * @param url               计算服务器地址
     * @param jarPath           规则包路径
     * @param bomMappingPath    映射文件路径
     * @param deploySettingPath 部署文件路径
     * @param userName          用户名
     * @param password          密码
     * @param ruleProj          工程代码
     * @return 上传信息
     */
    public static String deployRulePackage(String url,
                                           String jarPath,
                                           String bomMappingPath,
                                           String deploySettingPath,
                                           String userName,
                                           String password,
                                           String ruleProj) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        FileBody fileBodyJar = new FileBody(new File(jarPath));
        FileBody fileBodyBom = new FileBody(new File(bomMappingPath));
        FileBody fileBodyDep = new FileBody(new File(deploySettingPath));

        StringBody stringBodyuserName = new StringBody(userName);
        StringBody stringBodypassword = new StringBody(password);
        StringBody stringBodyruleProj = new StringBody(ruleProj);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("RulePackage.jar", fileBodyJar);
        entity.addPart("RuleBomMapping.xml", fileBodyBom);
        entity.addPart("RuleDeploy.xml", fileBodyDep);
        entity.addPart("userName", stringBodyuserName);
        entity.addPart("password", stringBodypassword);
        entity.addPart("ruleObjectName", stringBodyruleProj);

        post.setEntity(entity);
        HttpResponse response = httpclient.execute(post);
        String result = "";
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

            HttpEntity entitys = response.getEntity();
            if (entity != null) {
//                System.out.println(entity.getContentLength());  
//                System.out.println(EntityUtils.toString(entitys)); 
                result = EntityUtils.toString(entitys);
            }
        }
        httpclient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * RuleDeploy.xml and RuleBomMapping.xml 已经在jar包，只是传jar包
     */
    public static String deployRulePackage(String url,
                                           String jarPath,
                                           String userName,
                                           String password,
                                           String deployCode,
                                           String ruleProj) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        FileBody fileBodyJar = new FileBody(new File(jarPath));

        StringBody stringBodyuserName = new StringBody(userName);
        StringBody stringBodypassword = new StringBody(password);
        StringBody stringBodyruleProj = new StringBody(ruleProj);
        StringBody stringBodyDeployCode = new StringBody(deployCode);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("RulePackage.jar", fileBodyJar);
        entity.addPart("userName", stringBodyuserName);
        entity.addPart("password", stringBodypassword);
        entity.addPart("ruleObjectName", stringBodyruleProj);
        entity.addPart("deployCode", stringBodyDeployCode);

        post.setEntity(entity);
        HttpResponse response = httpclient.execute(post);
        String result = "";
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

            HttpEntity entitys = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entitys);
            }
        } else {
            result = response.toString();
        }
        httpclient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * RuleDeploy.xml and RuleBomMapping.xml 已经在jar包，只是传jar包
     */
    public static String deployRuleDataPackage(String url,
                                               String invokePoint,
                                               String userName,
                                               String password,
                                               String deployCode,
                                               String ruleProj) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);


        List<NameValuePair> pairs = new ArrayList<NameValuePair>();

        NameValuePair pair1 = new BasicNameValuePair("userName", userName);
        NameValuePair pair2 = new BasicNameValuePair("password", password);
        NameValuePair pair3 = new BasicNameValuePair("ruleObjectName", ruleProj);
        NameValuePair pair4 = new BasicNameValuePair("invokePoint", invokePoint);

        pairs.add(pair1);
        pairs.add(pair2);
        pairs.add(pair3);
        pairs.add(pair4);


        post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(post);
        String result = "";
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

            HttpEntity entitys = response.getEntity();
            if (entitys != null) {
                result = "Yes";
            }

        } else {
            result = response.toString();
        }
        httpclient.getConnectionManager().shutdown();
        return result;
    }

    public static void post() throws IOException {
        String path = "E:/workplace/ruleDev/RuleRepository/myproj/deployOnline/deploy1fodtNBI";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://172.19.0.121:8080/TansunRuleExcuter/deploy/depolyRuleJar.do");
        FileBody fileBodyJar = new FileBody(new File(path + "/rulePackage.jar"));
        FileBody fileBodyBom = new FileBody(new File(path + "/packageDir/ruleBomMapping.xml"));
        FileBody fileBodyDep = new FileBody(new File(path + "/packageDir/deploy.xml"));

        StringBody stringBodyuserName = new StringBody("admin");
        StringBody stringBodypassword = new StringBody("thepass");
        StringBody stringBodyruleProj = new StringBody("myproj");

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("RulePackage.jar", fileBodyJar);
        entity.addPart("RuleBomMapping.xml", fileBodyBom);
        entity.addPart("RuleDeploy.xml", fileBodyDep);
        entity.addPart("userName", stringBodyuserName);
        entity.addPart("password", stringBodypassword);
        entity.addPart("ruleObjectName", stringBodyruleProj);

        post.setEntity(entity);
        HttpResponse response = httpclient.execute(post);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

            HttpEntity entitys = response.getEntity();
            if (entity != null) {
                System.out.println(entity.getContentLength());

                System.out.println(EntityUtils.toString(entitys));
            }
        } else {
            System.err.println("error");
        }
        httpclient.getConnectionManager().shutdown();
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> post(Map<String, Object> request, String url, final int timeout)
            throws Exception {
        return JsonUtils.parse(post(JsonUtils.assemble(request), url, timeout), Map.class);
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> post(Map<String, Object> request, String url) throws Exception {
        return JsonUtils.parse(post(JsonUtils.assemble(request), url, 30000), Map.class);
    }

    /**
     * 发送POST请求,MIME type：application/json，charset:UTF-8
     */
    public static <T> T post(Object request, String url, final int timeout, Class<T> responseType) throws Exception {
        return JsonUtils.parse(post(JsonUtils.assemble(request), url, timeout), responseType);
    }

    /**
     * 发送POST请求，默认超时时间是30秒
     */
    public static <T> T post(Object request, String url, Class<T> responseType) throws Exception {
        return post(request, url, 30000, responseType);
    }

    /**
     * 发送POST请求,MIME type：application/json，charset:UTF-8
     */
    public static String post(String request, String url, final int timeout) throws Exception {
        logger.debug("请求地址:{}，请求报文：{} ", url, request);

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout)
                .build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        HttpPost httppost = new HttpPost(url);
        HttpEntity requestEntity = new StringEntity(request, ContentType.APPLICATION_JSON);
        httppost.setEntity(requestEntity);
        try {
            CloseableHttpResponse httpResponse = client.execute(httppost);
            try {
                if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                    String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
                    logger.debug("请求地址:{}，反馈报文：{} ", url, response);
                    return response;
                } else {
                    throw new Exception("服务调用异常,返回码：" + httpResponse.getStatusLine().getStatusCode());
                }
            } finally {
                httpResponse.close();
            }
        } finally {
            client.close();
        }

    }

    /**
     * 发送POST请求，默认超时时间是30秒
     */
    public static String post(String request, String url) throws Exception {
        return post(request, url, 30000);
    }
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
